/**
 * copyright (c) 2017-2023 厦门风领科技有限公司
 * https://www.fengling.cn/
 * 
 * zengbinsi
 * 2019-01-19
 */

const path = require('path'),
fs = require('fs');
const exec = require('child_process').exec;

if (!Editor.Project.path) {
    Editor.Project.path = Editor.Project.path;
}

/** 编辑器安装资源目录 */
exports.pathEditorAppResRoot = Editor.App.path.substr(0, Editor.App.path.indexOf('app.asar') - 1);

/** 项目根目录 */
exports.pathProject = Editor.Project.path;
exports.getPathInProject = (pathName)=>path.join(Editor.Project.path, pathName);

/** 项目资源目录 */
exports.pathAssets = path.join(Editor.Project.path, 'assets');
exports.getPathInAssets = (pathName)=>path.join(Editor.Project.path, 'assets', pathName);

/** 项目框架目录 */
exports.pathFramework = path.join(Editor.Project.path, 'assets', 'framework');
exports.getPathInFramework = (pathName)=>path.join(Editor.Project.path, 'assets', 'framework', pathName);

/** 项目编译模板目录 */
exports.pathBuildTemplates = path.join(Editor.Project.path, 'build-templates');
exports.getPathInBuildTemplates = (pathName)=>path.join(Editor.Project.path, 'build-templates', pathName);

/** 项目编译目录 */
exports.pathBuild = path.join(Editor.Project.path, 'build');
exports.getPathInBuild = (pathName)=>path.join(Editor.Project.path, 'build', pathName);




/** 插件根目录 */
exports.pathPackageRoot = path.join(__dirname, '..', '..');
exports.getPathInPackage = (pathName)=>path.join(__dirname, '..', '..', pathName);

/** 插件运行时文件目录 */
exports.pathPackageRuntimeAssets = path.join(__dirname, '..', '..', 'runtime-assets');
exports.getPathInPackageRuntime = (pathName)=>path.join(__dirname, '..', '..', 'runtime-assets', pathName);

/** 插件资源目录 */
exports.pathTemplateAssets = path.join(__dirname, '..', '..', 'templates', 'assets-template');
exports.getPathInTemplateAssets = (pathName)=>path.join(__dirname, '..', '..', 'templates', 'assets-template', pathName);

/** 插件框架目录 */
exports.pathTemplateFramework = path.join(__dirname, '..', '..', 'templates', 'framework-template');
exports.getPathInTemplateFramework = (pathName)=>path.join(__dirname, '..', '..', 'templates', 'framework-template', pathName);

/** 插件编译模板目录 */
exports.pathInTemplateBuild = path.join(__dirname, '..', '..', 'templates', 'build-templates-template');
exports.getPathInTemplateBuild = (pathName)=>path.join(__dirname, '..', '..', 'templates', 'build-templates-template', pathName);

/** 插件编辑器模板目录 */
exports.pathInTemplateEditor = path.join(__dirname, '..', '..', 'templates', 'editor-template');
exports.getPathInTemplateEditor = (pathName)=>path.join(__dirname, '..', '..', 'templates', 'editor-template', pathName);


/** 插件工具目录 */
exports.pathPackageTools = path.join(__dirname, '..', '..', 'tools');
exports.getPathInPackageTools = (pathName)=>path.join(__dirname, '..', '..', 'tools', pathName);


/**
 * 格式化路径
 * @param {string} filePath 路径
 * @param {string} splitChar 分隔符
 */
exports.formatPath = (filePath, splitChar)=>{
    const dirs = filePath.split(splitChar || '/');
    return path.join(...dirs);
};


/**
 * 创建文件夹
 * @param {*} dirPath 路径
 * @param {*} mode 
 */
exports.mkPathSync = (dirPath, mode)=>{
    try {
        if (!fs.existsSync(dirPath)) {
            console.log('[tool-box]Creator ' + dirPath + ' path...');

            let pathtmp;
            dirPath.split(/[/\\]/).forEach((dirname)=>{
                if (pathtmp) {
                    pathtmp = path.join(pathtmp, dirname);
                } else {
                    pathtmp = dirname;
                }

                if (pathtmp !== '' && !fs.existsSync(pathtmp)) {
                    if (!fs.mkdirSync(pathtmp, mode)) {
                        return false;
                    }
                }
            });
        }
        return true;
    } catch (e) {
        console.error("create path fail! path=" + dirPath +" errorMsg:" + e);
        return false;
    }
};

/**
 * 创建assets文件夹
 * @param {string} dirPath 从Assets根目录开始的路径
 * @param {*} callback 回调
 */
exports.mkdirsSyncInAssets = (dirPath, callback)=>{
    try {
        if (!Editor.assetdb.exists(`db://assets/${dirPath}`)) {
            console.log('[tool-box]Creator ' + dirPath + ' path...');

            const paths = dirPath.split(/[/\\]/);
            const createDir = (pathtmp)=>{
                if (!Editor.assetdb.exists(`db://assets/${pathtmp}`)) {
                    Editor.assetdb.create(`db://assets/${pathtmp}`, null, ()=>{
                        paths.splice(0, 1);
                        if (paths[0]) {
                            // 递归创建文件夹
                            return createDir(path.join(pathtmp, paths[0]));
                        }
                        console.log('[tool-box]Creator ' + pathtmp + ' path successed!')
                        
                        callback && callback();
                        return ;
                    });
                } else {
                    paths.splice(0, 1);
                    if (paths[0]) {
                        // 递归创建文件夹
                        return createDir(path.join(pathtmp, paths[0]));
                    }
                }
            };

            if (paths[0]) {
                return createDir(paths[0]);
            }
        } else {
            console.log('[tool-box]' + dirPath + ' exists!');
            callback && callback();
        }
        return true;
    } catch (e) {
        console.error("create path fail! path=" + dirPath +" errorMsg:" + e);
        return false;
    }
};




/**
 * 文件遍历方法
 * @param filePath 需要遍历的文件路径
 * @param needFile 需要遍历的文件格式(png，js, ts, jpg, json...)
 * @param isNotRecursion 是否不进行递归
 */
const dumpAllFiles = (filePath, needFile, isNotRecursion)=>{
    let result = [];

    // 根据文件路径读取文件，返回文件列表
    try {
        const filePaths = fs.readdirSync(filePath);
        let filedir, stats;

        // 遍历读取到的文件列表
        filePaths.forEach((filename)=>{
            // 获取当前文件的绝对路径
            filedir = path.join(filePath, filename);

            try {
                // 根据文件路径获取文件信息，返回一个fs.Stats对象
                stats = fs.statSync(filedir);
                if(stats.isFile()){
                    if (needFile && path.extname(filename) !== `.${needFile}`) {
                    } else {
                        result.push(filedir);    
                    }
                } else if(!isNotRecursion && stats.isDirectory()){
                    // 递归，如果是文件夹，就继续遍历该文件夹下面的文件
                    result = [...result, ...dumpAllFiles(filedir, needFile, isNotRecursion)];
                }
            } catch(err) {
                console.warn('获取文件stats失败:', filedir, err);
            }
        });
    } catch (error) {
        console.error(err);
    }

    return result;
};

/**
 * 拷贝文件夹
 * @param {*} srcDir 要拷贝的文件夹
 * @param {*} destDir 存放目录
 */
 exports.copyDirs = (srcDir, destDir, callback)=>{
    console.log('[tool-box]mkdirs:', destDir);
    pathUtil.mkPathSync(destDir);

    console.log('[tool-box]copy:', srcDir, destDir);
    const sh = `cp -rf ${srcDir} ${destDir}`;
    exec(sh, (err, stdout, stderr) => {
        if (err || stderr) { return console.log('[tool-box]copy failed', err, stderr); }

        callback && callback();
    });
};

exports.dumpAllFiles = dumpAllFiles;


